<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div>
    <div id="connect-container" class="ui centered grid">
        <div class="row">
            <button id="connect" onclick="connect();" class="ui green button ">Connect</button>
            <button id="disconnect" disabled="disabled" onclick="disconnect();"
                    class="ui red button">Disconnect
            </button>
        </div>
        <div class="row">
            <label for="message"></label><textarea id="message" style="width: 350px" class="ui input"
                                                   placeholder="Message to Echo"></textarea>
        </div>
        <div class="row">
            <button id="echo" onclick="echo();" disabled="disabled"
                    class="ui button">Echo message
            </button>
        </div>
    </div>
    <div id="console-container">
        <h3>Logging</h3>
        <div id="logging"></div>
    </div>
</div>
<script type="text/javascript">
    var ws = null;
    var url = "ws://localhost:8080/chat?userId=123456789";

    function setConnected(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disconnect').disabled = !connected;
        document.getElementById('echo').disabled = !connected;
    }

    function connect() {
        ws = new WebSocket(url);
        ws.onopen = function () {
            setConnected(true);
            log('Info: Connection Established.');
        };

        ws.onmessage = function (event) {
            log(event.data);
        };

        ws.onclose = function (event) {
            setConnected(false);
            log('Info: Closing Connection.');
        };
    }

    function disconnect() {
        if (ws != null) {
            ws.close();
            ws = null;
        }
        setConnected(false);
    }

    function echo() {
        if (ws != null) {
            var message = document.getElementById('message').value;
            log('Sent to server :: ' + message);
            ws.send(message);
        } else {
            alert('connection not established, please connect.');
        }
    }

    function log(message) {
        var console = document.getElementById('logging');
        var p = document.createElement('p');
        p.appendChild(document.createTextNode(message));
        console.appendChild(p);
    }
</script>
</body>
</html>